﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net;
using System.IO;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
using System.Web;
using System.Net;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.IO;
using System.Linq;

namespace WechatSDK
{
    public partial class AddLog : System.Web.UI.Page
    {

        public static string Flag = "0";

        public static string LogFlag;
        static string chinesename = "";
        static string username = "";
        string tokenValue = "";
        static string phone = "";
        static public string appId = "";
        static public string timestamp = "";
        static public string nonceStr = "";
        static public string signature = "";

        public static int imgcount = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                imgcount = 0;
                LogFlag = Guid.NewGuid().ToString();
               
            }

            Flag = Request["Flag"].Trim().ToString();
           
            // eqname.Visible = false;


            Hashtable ht = JSSDK.getSignPackage();
            appId = ht["appId"].ToString();
            nonceStr = ht["nonceStr"].ToString();
            timestamp = ht["timestamp"].ToString();
            signature = ht["signature"].ToString();
            try
            {
                //1.微信主页判断是否存在Cookie信息，如果存在则不需要再次验证
                //2.如果不存在，则跳转到微信OAuth统一认证页面认证，之后到此页面获取用户信息存入Cookie返回主页
                //3.获取Code,此code只能使用一次。
                string code = Request["code"];

                //4.根据企业ID:XX,Secret:XXX,获取token
                string accessTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
                string accessTokenResult = HttpGet(accessTokenUrl, "corpid=wx8579b2dae40753d2&corpsecret=JjVqfS47AEc9Z9UHhDvksIGZ_YPgW6Wjo80jGOTxKX8m8yn4VoHDaxRXJI43dIa5");


                JavaScriptSerializer js = new JavaScriptSerializer();
                token mytoken = js.Deserialize<token>(accessTokenResult);
                tokenValue = mytoken.access_token;


                //5.获取UserInfo,包含userId
                string userinfoUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo";
                string userinfojson = HttpGet(userinfoUrl, "access_token=" + tokenValue + "&code=" + code);

              
                //dscr.Value = userinfojson;
                userinfo userinfo1 = js.Deserialize<userinfo>(userinfojson);
                string UserId = userinfo1.UserId;


                //6.根据userId获取通讯录中用户的详细信息
                string userinfodetailURL = "https://qyapi.weixin.qq.com/cgi-bin/user/get";
                string userinfodetailResult = HttpGet(userinfodetailURL, "access_token=" + tokenValue + "&userid=" + UserId);
                // JObject jObject = (JObject)JsonConvert.DeserializeObject(userinfodetailResult);
                // JObject ja = (JObject)JsonConvert.DeserializeObject(jObject["extattr"].ToString());
                // JObject ja2 = (JObject)JsonConvert.DeserializeObject(jObject["mobile"].ToString());
                // JArray jObject1 = (JArray)JsonConvert.DeserializeObject(ja["attrs"].ToString());
                //txtReturn2.Text = ja[0]["MainOrganization"].ToString();

                //测试结果
                //Response.Write("1:token:" + accessTokenResult + "<br/>2:tokenValue:" + tokenValue + "<br/>3:code:" + code + "<br/>4:userinfojson:" + userinfojson + "<br/>5.UserId:" + UserId + "<br/>6.userinfodetailResult:" + userinfodetailResult + "<br/>7:数组：" + jObject1[0]["value"].ToString());

                //7.将Guid存入cookie


                //string userguid = jObject1[0]["value"].ToString();
                // Response.Cookies["UserGuid"].Value = userguid;
                // Response.Cookies["UserGuid"].Expires = DateTime.Now.AddDays(1);



                string[] sArray = userinfodetailResult.Split(new string[] { "mobile", "gender" }, StringSplitOptions.RemoveEmptyEntries);
                string[] sArray2 = userinfodetailResult.Split(new string[] { "name", "department" }, StringSplitOptions.RemoveEmptyEntries);
                string[] sArray3 = userinfodetailResult.Split(new string[] { "userid", "name" }, StringSplitOptions.RemoveEmptyEntries);



                username = sArray3[1];
                username = username.Replace("\"", "");
                username = username.Replace(":", "");
                username = username.Replace(",", "");

                chinesename = sArray2[1];
                chinesename = chinesename.Replace("\"", "");
                chinesename = chinesename.Replace(":", "");
                chinesename = chinesename.Replace(",", "");

                phone = sArray[1];
                phone = phone.Replace("\"", "");
                phone = phone.Replace(":", "");
                phone = phone.Replace(",", "");
                // Label1.Text = str;




            }
            catch (Exception ex)
            {
                //TODO 处理异常

            }










        }

        protected void Button1_Click(object sender, EventArgs e)
        {

        }

        protected void Button1_Click1(object sender, EventArgs e)
        {
            imgcount++;
            System.Collections.Specialized.NameValueCollection nc = new System.Collections.Specialized.NameValueCollection(Request.Form);


            string mediaid = nc.GetValues("hide_file")[0].ToString();

            if (imgcount == 1)
            {
                Image1.ImageUrl = mediaid;

                Image2.ImageUrl = "dist/example/images/plus.png";
            }

            if (imgcount == 2)
            {
                Image2.ImageUrl = mediaid;
                Image3.ImageUrl = "dist/example/images/plus.png";
            }
            if (imgcount == 3)
            {
                Image3.ImageUrl = mediaid;
                Image4.ImageUrl = "dist/example/images/plus.png";
            }
            if (imgcount == 4)
            {
                Image4.ImageUrl = mediaid;

            }

            DBS d = new DBS();
            d.Add_Task_Log_File(LogFlag, nc.GetValues("serverid")[0].ToString(), "jpg", tokenValue);

        }

        protected void Button3_Click(object sender, EventArgs e)
        {

        }

        protected void Button4_Click(object sender, EventArgs e)
        {

        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            Button2.Enabled = false;





            DBS m = new DBS();


            m.Add_Task_Log(LogFlag,Flag, dscr.Value.ToString(), chinesename);


          
            Response.Redirect("Finish_Close.aspx");


        }



        public class userinfo
        {
            public string UserId { get; set; }
            public string DeviceId { get; set; }
        }

        public class token
        {

            public string access_token { get; set; }
            public int expires_in { get; set; }

        }





        public string PostWebRequest(string postUrl, string paramData, Encoding dataEncode)
        {
            string ret = string.Empty;
            try
            {
                byte[] byteArray = dataEncode.GetBytes(paramData); //转化
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
                webReq.Method = "POST";
                webReq.ContentType = "application/x-www-form-urlencoded";

                webReq.ContentLength = byteArray.Length;
                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
                ret = sr.ReadToEnd();
                sr.Close();
                response.Close();
                newStream.Close();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return ret;
        }
        public string HttpGet(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }



    }
}